import { Logger } from '@nestjs/common'
import { WebSocketGateway, SubscribeMessage, OnGatewayConnection, WebSocketServer, WsResponse,OnGatewayInit, OnGatewayDisconnect } from '@nestjs/websockets'
import { EMPTY, Observable } from 'rxjs';
import { ClientManager ,CmdType } from './type/ws.user.context';
import * as dateformat from 'dateformat'

@WebSocketGateway({ path: "/ws" })
export class WebSocketServerGeteWay implements OnGatewayConnection,OnGatewayInit,OnGatewayDisconnect {

    readonly clientManager: ClientManager = new ClientManager();

    constructor() { }

    handleDisconnect(client: any) {
        this.logger.debug("连接断开");
        this.clientManager.removeClient( client.loginUser,client);
        
    }
    afterInit(server: any) {
        this.logger.debug("初始化服务");
        
    }

    handleConnection(client: any, ...args: any[]) {
        this.logger.debug("客户链接..");
    }
 

    private readonly logger: Logger = new Logger(WebSocketServerGeteWay.name);

    @SubscribeMessage(undefined)
    onEvent(client: any, data: any): Observable<any> {
       if(data.cmdType==CmdType.LOGIN){

        // 登录命令

            if(this.clientManager.addClient(data.name,client)){

                client.loginUser = data.name;

                let youMsg = {
                    cmdType: CmdType.SYSTEM,
                    msg:`${data.name}进入聊天室`,
                    type:1,
                    showType:1,
                    sendTime:dateformat(new Date(),"yyyy-MM-dd HH:mm:ss")
                }

                let meMsg = {
                    cmdType: CmdType.SYSTEM,
                    msg:"欢迎你登陆聊天室",
                    type:1,
                    showType:1,
                    sendTime:dateformat(new Date(),"yyyy-MM-dd HH:mm:ss")
                }
              
                this.clientManager.send((n,c)=>{
                    // 给自己发送
                    if(n === data.name){
                        c.send(meMsg)
                    }else {
                        // 给其他用户发送
                        c.send(youMsg)
                    }
                })
            }
        
      }else if(data.cmdType==CmdType.CHAT){
        // 聊天命令

        let youMsg = {
            cmdType: 2,
            msg:data.msg,
            type:1,
            showType:1,
            sender:client.loginUser,
            sendTime:dateformat(new Date(),"yyyy-MM-dd HH:mm:ss")
        }

        let meMsg = {
            cmdType: 1,
            msg:data.msg,
            type:1,
            showType:1,
            sender:client.loginUser,
            sendTime:dateformat(new Date(),"yyyy-MM-dd HH:mm:ss")
        }
      


        this.clientManager.send((n,c)=>{
            // 给自己发送
            if(n === client.loginUser){
                c.send(meMsg)
            }else {
                // 给其他用户发送
                c.send(youMsg)
            }
        })

      }
      return EMPTY;
    }

}